package com.example.android.unscramble.ui.game

import android.text.Spannable
import android.text.SpannableString
import android.text.style.TtsSpan
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel

class GameViewModel: ViewModel() {

    private var wordsList: MutableList<String> = mutableListOf()

    private val _score = MutableLiveData(0)
    val score: LiveData<Int> get() = _score

    private var _count = MutableLiveData(0)
    val count: LiveData<Int> get() = _count

    private val _word = MutableLiveData<String>()
    // 让屏幕阅读器逐个字母读出乱序单词
    // live data 转换, 类似 vue 的 computed 属性
    val word: LiveData<Spannable> = Transformations.map(_word) {
        if (it == null) {
            SpannableString("")
        } else {
            val scrambledWord = it.toString()
            val spannable: Spannable = SpannableString(scrambledWord)
            spannable.setSpan(
                TtsSpan.VerbatimBuilder(scrambledWord).build(),
                0,
                scrambledWord.length,
                Spannable.SPAN_INCLUSIVE_INCLUSIVE
            )
            spannable
        }
    }

    private lateinit var answer: String

    companion object {
        const val TAG = "### GameViewModel"
    }

    init {
        Log.d(TAG, "init{}")
        init()
    }

    fun init() {
        wordsList.clear()
        _score.value = 0
        _count.value = 0
        nextWord() // 为 _word 和 answer 赋值
    }

    override fun onCleared() {
        super.onCleared()
        Log.d(TAG, "onCleared()")
    }

    private fun nextWord() {
        // 取出一个新单词
        answer = allWordsList.random()
        while (wordsList.contains(answer)) {
            answer = allWordsList.random()
        }
        wordsList.add(answer)

        // 打乱这个单词
        val tempWord = answer.toCharArray()
        while (String(tempWord) == answer) {
            tempWord.shuffle()
        }
        // 增加计数
        _count.value = _count.value?.inc()
        _word.value = String(tempWord)
    }

    fun nextWordLimit(limit: Int = MAX_NO_OF_WORDS): Boolean {
        if (count.value!! >= limit) return false
        nextWord()
        return true
    }

    private fun increaseScore() {
        _score.value = _score.value?.plus(SCORE_INCREASE)
    }

    fun isCorrect(playerWord: String): Boolean {
        Log.d(TAG, answer)
        if (playerWord.equals(answer, true)) {
            increaseScore()
            return true
        }
        return false
    }
}